package com.bruce.springai.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bruce.springai.dto.UserDTO;
import com.bruce.springai.dto.UserQueryDTO;
import com.bruce.springai.entity.UserEntity;
import com.bruce.springai.mapper.UserMapper;
import com.bruce.springai.service.UserService;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper,UserEntity> implements UserService{

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);


    @Override
    public UserDTO findOne(UserQueryDTO queryDTO){

        LambdaQueryWrapper<UserEntity>  queryWrapper = this.generateQueryWrapper(queryDTO) ;
        queryWrapper.last("limit 1");
        UserEntity userEntity = baseMapper.selectOne(queryWrapper) ;

        if(userEntity == null){
            logger.info("找不到该用户的记录");
           return null ;
        }

        UserDTO userDTO = new UserDTO() ;
        BeanUtils.copyProperties(userEntity, userDTO);

        return userDTO ;
    }


    /**
     * 组装查询条件
     * @param queryDTO
     * @return
     */
    private LambdaQueryWrapper<UserEntity> generateQueryWrapper(UserQueryDTO queryDTO){
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<UserEntity>() ;
        Long userId = queryDTO.getUserId() ;
        if(userId != null && userId > 0){
            queryWrapper.eq(UserEntity::getUserId, queryDTO.getUserId()) ;
        }
        if(StringUtils.isNotBlank(queryDTO.getUserName())){
            queryWrapper.eq(UserEntity::getUserName, queryDTO.getUserName()) ;
        }
        if(StringUtils.isNotBlank(queryDTO.getCity())){
            queryWrapper.eq(UserEntity::getCity, queryDTO.getCity()) ;
        }

        Integer status = queryDTO.getStatus() ;
        if(status != null && status > 0){
            queryWrapper.eq(UserEntity::getStatus, status) ;
        }
        queryWrapper.orderByDesc(UserEntity::getCreateTime) ;
        return queryWrapper ;
    }


    @Override
    public boolean save(UserDTO userDTO) {
        UserEntity entity = UserEntity.builder().build() ;
        BeanUtils.copyProperties(userDTO, entity);
        return  save(entity) ;
    }

}
